package com.example.administrator.officeplatform.kj;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.administrator.officeplatform.Activity.HomeActivity;
import com.example.administrator.officeplatform.Audit.AuditAdapter;
import com.example.administrator.officeplatform.Audit.AuditDetailActivity;
import com.example.administrator.officeplatform.Audit.AuditInfo;
import com.example.administrator.officeplatform.MyApplication;
import com.example.administrator.officeplatform.R;
import com.example.administrator.officeplatform.adapter.BMSearchAdapter;
import com.example.administrator.officeplatform.base.BaseActivity;
import com.example.administrator.officeplatform.bean.BMInfo;
import com.example.administrator.officeplatform.utils.JsonUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BMSearchActivity extends BaseActivity {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.sv)
    SearchView sv;
    @Bind(R.id.rv)
    RecyclerView rv;
    private Context mContext;
    private List<RelativeLayout> ls_rl;
    private List<View> ls_v;
    private List<BMInfo> ls_audit;
    private BMSearchAdapter bmSearchAdapter;
    private OkHttpClient mOkHttpClient;
    private String newtext = "";
    private String type,index;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_bmsearch);

    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        mContext=this;
        //设置布局管理器
        rv.setLayoutManager(new LinearLayoutManager(mContext));
        rv.setHasFixedSize(true);
        rv.setItemAnimator(new DefaultItemAnimator());

        type=(String)getIntent().getExtras().get("type");
        if(type.equals("1")||type.equals("2")){
            index=(String)getIntent().getExtras().get("index");
        }

    }

    @Override
    protected void initData() {
        ls_audit= new ArrayList<>();
        search();
//        bmSearchAdapter.setOnRecyclerViewListener(new BMSearchAdapter.OnRecyclerViewListener() {
//            @Override
//            public void onItemClick(int position) {
//                Intent mIntent = new Intent();
//                //把返回数据存入Intent
//                mIntent.putExtra("index", "1");
//                //设置返回数据
//                setResult(2, mIntent);
//                finish();
//            }
//
//            @Override
//            public boolean onItemLongClick(int position) {
//                return false;
//            }
//        });
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            // 当搜索内容改变时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                newtext = newText;
                search();
                return false;
            }
        });
    }

    private void search(){

        mOkHttpClient = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("name", newtext);
        String json = JSON.toJSONString(map);
        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
//                .url("http://192.168.5.37:8686/reimbursement/dictionaries/getVagueOrgName/财务")
                .url(IpUtil.getIP()+"/reimbursement/dictionaries/getVagueOrgName")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Map<String,String> map1 = JsonUtil.getPerson(str,Map.class);
                ls_audit.clear();
                for (Map.Entry<String, String> entry : map1.entrySet()) {
                    BMInfo bmInfo = new BMInfo();
                    bmInfo.setName(entry.getValue().toString());
                    bmInfo.setId(entry.getKey().toString());
                    ls_audit.add(bmInfo);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ls_audit.size()==0){
                            Toast.makeText(mContext, "未查询到部门信息", Toast.LENGTH_SHORT).show();
                        }
                        if(bmSearchAdapter==null){
                            bmSearchAdapter=new BMSearchAdapter(ls_audit,mContext);
                            rv.setAdapter(bmSearchAdapter);
                        }else{
                            bmSearchAdapter.notifyDataSetChanged();
                        }
                        bmSearchAdapter.setOnRecyclerViewListener(new BMSearchAdapter.OnRecyclerViewListener() {
                            @Override
                            public void onItemClick(int position) {
                                if(type.equals("0")){
                                    Intent mIntent = new Intent();
                                    BMInfo bmInfo = ls_audit.get(position);
                                    //把返回数据存入Intent
                                    mIntent.putExtra("index", bmInfo.getName());
                                    mIntent.putExtra("departId",bmInfo.getId());
                                    //设置返回数据
                                    setResult(2, mIntent);
                                    finish();
                                }else if(type.equals("1")){
                                    Intent mIntent = new Intent();
                                    BMInfo bmInfo = ls_audit.get(position);
                                    //把返回数据存入Intent
                                    mIntent.putExtra("index",index);
                                    mIntent.putExtra("name",bmInfo.getName());
                                    mIntent.putExtra("departId",bmInfo.getId());
                                    //设置返回数据
                                    setResult(5, mIntent);
                                    finish();
                                }else if(type.equals("2")){
                                    Intent mIntent = new Intent();
                                    BMInfo bmInfo = ls_audit.get(position);
                                    //把返回数据存入Intent
                                    mIntent.putExtra("index",index);
                                    mIntent.putExtra("name",bmInfo.getName());
                                    mIntent.putExtra("departId",bmInfo.getId());
                                    //设置返回数据
                                    setResult(6, mIntent);
                                    finish();
                                }
                            }

                            @Override
                            public boolean onItemLongClick(int position) {
                                return false;
                            }
                        });

                    }
                });
            }

        });


    }
}
